import { ref } from 'vue'
import { defineStore } from 'pinia'
import { computedAsync } from '@vueuse/core'
import cfg from '@/config/config'
import api from '@/api/lesson'
import type { LessonSearchForm, LessonPostForm } from '@/config/forms'
import type { PageConfig, LessonItem, ContentItem } from '@/config/types'
import { useCategotryStore } from './category'


export const useLessonStore = defineStore('lessons', () => {
  const loading = ref<boolean>(false)
  const search = ref<LessonSearchForm>({
    title: '',
    categoryId: 0,
    recommend: null,
    onself: null,
    year: '',
    minPrice: null,
    maxPrice: null,
    page: 1,
    limit: cfg.pageLimit
  })
  const lessons = ref<LessonItem[]>([])
  const pager = ref<PageConfig>({
    page: 1,
    pageSize: cfg.pageLimit,
    total: 0
  })

  const updating = ref<boolean>(false)
  const lesson = ref<LessonItem | null>(null)

  const contentItem = ref<ContentItem>({
    id: 0,
    content: ''
  })

  const categories = computedAsync(async () => {
    const store = useCategotryStore()
    await store.loadCategories(false)
    return store.categories
  }, [])

  async function loadLessons() {
    //如果是数组抽取最后一个id
    if (search.value.categoryId instanceof Array && search.value.categoryId.length > 0) {
      search.value.categoryId = search.value.categoryId.pop()
    }
    loading.value = true
    try {
      const res = await api.getList(search.value)
      lessons.value = res.data
      pager.value.total = res.total
      pager.value.pageSize = res.size
      pager.value.page = res.page
      loading.value = false
    } catch (e) {
      loading.value = false
    }
  }

  function changePage(page: number, size: number) {
    search.value.page = page
    search.value.limit = size
    loadLessons()
  }

  async function loadLesson(id: number, reload = true) {
    if (lesson.value != null && lesson.value.id === id && !reload) return

    updating.value = true
    try {
      const res = await api.getItem(id)
      lesson.value = res.data
      updating.value = false
    } catch (e) {
      updating.value = false
    }
  }

  async function removeLesson(id: number) {
    loading.value = true
    try {
      const res = await api.delete(id)
      loading.value = false
      return res.data
    } catch (e) {
      loading.value = false
    }
    return false
  }

  function newLesson() {
    lesson.value = {
      id: 0,
      title: '',
      categoryId: 0,
      categoryTitle: '',
      thumb: '',
      summary: '',
      price: 0,
      marketPrice: 0,
      teachers: '',
      recommend: false,
      onself: false,
      sort: 0
    }
  }

  async function saveLesson() {
    updating.value = true
    let result = false
    try {
      if (lesson.value) {
        //如果是数组抽取最后一个id
        if (lesson.value.categoryId instanceof Array && lesson.value.categoryId.length > 0) {
          lesson.value.categoryId = lesson.value.categoryId.pop()
        }
        const form: LessonPostForm = {
          title: lesson.value.title,
          categoryId: lesson.value.categoryId as number,
          thumb: lesson.value.thumb,
          teachers: lesson.value.teachers,
          summary: lesson.value.summary,
          price: lesson.value.price,
          marketPrice: lesson.value.marketPrice,
          recommend: lesson.value.recommend,
          sort: lesson.value.sort
        }
        let res
        if (lesson.value.id > 0) {
          res = await api.update(lesson.value.id, form)
        } else {
          res = await api.create(form)
        }
        result = res.data
      }
      updating.value = false
    } catch (e) {
      updating.value = false
    }
    return result
  }

  async function loadContent(id: number) {
    updating.value = true
    try {
      const res = await api.getContent(id)
      contentItem.value = {
        id,
        content: res.data
      }
      updating.value = false
    } catch (e) {
      updating.value = false
    }
  }

  async function updateContent() {
    updating.value = true
    try {
      const item = contentItem.value
      const res = await api.updateContent(item.id, item.content)
      updating.value = false
      return res.data
    } catch (e) {
      updating.value = false
    }
    return false
  }

  async function updateOnself(val: boolean) {
    const ids = lessons.value.filter((item) => item.onself === val).map((item) => item.id)
    await api.onself(ids, val)
  }

  async function updateRecommend(val: boolean) {
    const ids = lessons.value.filter((item) => item.recommend === val).map((item) => item.id)
    await api.recommend(ids, val)
  }

  return {
    loading,
    search,
    lessons,
    categories,
    pager,
    loadLessons,
    changePage,
    updateOnself,
    updateRecommend,

    updating,
    lesson,
    contentItem,
    loadLesson,
    newLesson,
    removeLesson,
    saveLesson,
    loadContent,
    updateContent
  }
})
